filter
filter
只會讓滿足條件的值通過,filter
接受一個閉包作為引數,該閉包返回一個Bool型別的值,只有結果為true的資料才會被儲存下來
[1, 6, 15, 22].publisher
.filter { value in
value > 10
}
.sink(receiveCompletion: { _ in
print("finished")
}, receiveValue: { value in
print(value)
})
/*印出
15
22
finished
*/
compactMap
compactMap
和map
的功能類似,只是會自動過濾掉空的元素,它的引數中的閉包支援返回一個可選型別的引數,因此,我們可以把傳進來的資料直接返回,就這麼簡單的一個操作就實現了空值過濾
["1", nil, "2", nil, "3"].publisher
.compactMap { value -> Int? in
guard let v = value else {
return nil
}
return Int(v)
}
.sink(receiveCompletion: { _ in
print("finished")
}, receiveValue: { value in
print(value)
})
/*印出
1
2
3
finished
*/
removeDuplicates
removeDuplicates
過濾掉連續的重複值
[1, 1, 1, 2, 2, 1, 2, 3].publisher
.removeDuplicates()
.sink(receiveCompletion: { _ in
print("finished")
}, receiveValue: { value in
print(value)
})
/*印出
1
2
1
2
3
finished
*/
replaceEmpty/replaceNil/replaceError
如果上游Publisher 是個空的數據流,replaceEmpty
會發送指定的值
Empty<Int, Never>()
.replaceEmpty(with: 1)
.sink(receiveCompletion: { _ in
print("finished")
}, receiveValue: { value in
print(value)
})
/*印出
1
finished
*/
空的數據流:在收到
finish
事件前,從來沒有收到任何資料Empty:一個只發出完成事件的Publisher
將收到的nil
轉換為給定的值
[1, nil, 3].publisher
.replaceNil(with: -1)
.map { $0! }
.sink(receiveCompletion: { _ in
print("finished")
}, receiveValue: { value in
print(value)
})
/*印出
1
-1
3
finished
*/
如果上游Publisher 因錯誤而終止,replaceError
會發送指定的值
enum MyError: Error {
case failed
}
var subject = PassthroughSubject<Int, Error>()
subject
.replaceError(with: 0)
.sink(receiveCompletion: { completion in
print(completion)
}, receiveValue: { int in
print(int)
})
subject.send(1)
subject.send(2)
subject.send(completion: .failure(MyError.failed))